import { Component } from '@angular/core';
import { Store } from '@ngxs/store';
import { ShopAction } from '../store/shop.action';
import { ShopSelector } from '@shop/store/shop.selector';
import { AutoUnsubscribe } from 'ngx-auto-unsubscribe-decorator';

@Component({
  selector: 'app-list',
  template: `
    <div style="margin-bottom: 5px">
      <button nz-button nzType="primary" (click)="add()">添加</button>
      &nbsp;
      <span>购物车数量:{{(cartCount$|async) || 0}}</span>
    </div>
    <nz-row>
      <nz-col nzSpan="24">
        <nz-table #basicTable [nzData]="(list$|async)||[]">
          <thead>
          <tr>
            <th>名称</th>
            <th>价格</th>
            <th>简介</th>
            <th>操作</th>
          </tr>
          </thead>
          <tbody>
          <tr *ngFor="let data of basicTable.data">
            <td>{{data.name}}</td>
            <td>{{data.price}}</td>
            <td>{{data.desc}}</td>
            <td>
              <button nz-button nzSize="small" nzType="primary" (click)="addCart(data)">
                <span nz-icon nzType="plus"></span>
                添加到购物车
              </button>
              <nz-divider nzType="vertical"></nz-divider>
              <a (click)="edit(data)">编辑</a>
              <nz-divider nzType="vertical"></nz-divider>
              <a (click)="delete(data)">删除</a>
            </td>
          </tr>
          </tbody>
        </nz-table>
      </nz-col>
    </nz-row>
  `,
  styles: [],
})
export class ListComponent {
  @AutoUnsubscribe() cartCount$ = this.store.select(ShopSelector.cartCount);
  @AutoUnsubscribe() list$ = this.store.select(ShopSelector.list);

  constructor(
      private store: Store,
  ) {
  }

  add() {
    this.store.dispatch(new ShopAction.OpenModal());
  }

  edit(data: any) {
    this.store.dispatch(new ShopAction.OpenModal(data));
  }

  delete(data: any) {
    this.store.dispatch(new ShopAction.Delete(data));
  }

  addCart(data: any) {
    this.store.dispatch(new ShopAction.AddToCart(data));
  }
}
